package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.length() == 0 || password == null || password.length() == 0) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码非法");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.getUserByName(username);
        if(user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误: 001");
            return;
        }
        if(!password.equals(user.getPassword())) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误: 002");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //前端发起获取登录状态请求，判断 对应会话存在 且 会话中保存了user对象 ？ 返回200 ： 返回403
        HttpSession session = req.getSession(false);
        if(session == null) {
            //会话不存在，用户未登录
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            //user不存在，用户未登录 -> 要实现退出登录删掉user属性即可
            resp.setStatus(403);
            return;
        }

        resp.setStatus(200);//可以不写，默认就是200
    }
}
